package com.ltxtiyu.video.service;


import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.annotation.JsonAppend;
import com.ltxtiyu.video.bean.VideoInfoBean;
import com.ltxtiyu.video.cacheDao.ConfigCacheDao;
import com.ltxtiyu.video.cacheDao.UserCacheDao;
import com.ltxtiyu.video.cacheDao.VideoCacheDao;
import com.ltxtiyu.video.common.ConfigConstant;
import com.ltxtiyu.video.common.JsonTool;
import com.ltxtiyu.video.common.RetEnum;
import com.ltxtiyu.video.dao.ltx.ShareVideoLogDao;
import com.ltxtiyu.video.dao.ltx.UserSourceVideoDao;
import com.ltxtiyu.video.entity.ShareVideoLog;
import com.ltxtiyu.video.entity.User;
import com.ltxtiyu.video.entity.UserSourceVideo;
import com.ltxtiyu.video.entity.Video;
import com.ltxtiyu.video.service.app.VideoService;
import com.ltxtiyu.video.tool.AliTool;
import com.ltxtiyu.video.tool.ObjectTool;
import org.apache.commons.lang3.StringUtils;
import org.hashids.Hashids;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 视频
 */
@Service
public class VideoServiceImpl implements VideoService {
    public static final Logger _log = LoggerFactory.getLogger(VideoServiceImpl.class);

    @Autowired
    UserSourceVideoDao userSourceVideoDao;
    @Autowired
    VideoCacheDao videoCacheDao;
    @Autowired
    ShareVideoLogDao shareVideoLogDao;
    @Autowired
    ConfigCacheDao configCacheDao;
    @Autowired
    UserCacheDao userCacheDao;
    /**
     * 素材库集合
     * @param params
     * @return
     */
    @Override
    public String sourceVideoList(Map<String, String> params) {
        Integer userId = Integer.parseInt(params.get("userId"));
        Integer start = Integer.parseInt(params.get("start"));
        Integer rows = Integer.parseInt(params.get("rows"));
        Map<String, Object> page = new HashMap<>();
        page.put("userId",userId);
        page.put("start",start);
        page.put("rows",rows);
        List<UserSourceVideo> sourceVideoList = userSourceVideoDao.selectListByParams(page);
        List<Map<String,Object>> resultSourceVideoList = new ArrayList<>();
        for(UserSourceVideo sourceVideo : sourceVideoList){
            Map<String, Object> resultVideo = new HashMap<>();

            String playUrl = "";
            String coverUrl = "";
            String duration = "";
            Integer videoId = -1;
            try{
                videoId = sourceVideo.getVideoId();
                Video video = videoCacheDao.selectByPrimaryKey(videoId);
                if(video != null && video.getStatus() > 0){ // 视频可以正常播放
                    VideoInfoBean videoInfoBean = JSON.parseObject(video.getVideoInfo(), VideoInfoBean.class);
                    playUrl = videoInfoBean.getPlayUrl();
                    coverUrl = videoInfoBean.getCoverUrl();
                    duration = videoInfoBean.getDuration();
                }
            }catch (Exception e){
                _log.error(">>>>>>>>>>>>>获取视频信息失败, videoId:{}, 错误信息:{}", videoId, e);
            }
            resultVideo.put("id",videoId);
            resultVideo.put("playUrl",playUrl);
            resultVideo.put("coverUrl",coverUrl);
            resultVideo.put("duration",duration);

            // 素材视频信息
            Map<String, Object> resultSourceVideo = new HashMap<>();
            resultSourceVideo.put("id",sourceVideo.getId());
            resultSourceVideo.put("videoId",videoId);

            // 单例结果
            Map<String, Object> singleResultVideo = new HashMap<>();
            singleResultVideo.put("video", resultVideo);
            singleResultVideo.put("sourceVideo", resultSourceVideo);
            resultSourceVideoList.add(singleResultVideo);
        }
        Map<String, Object> result = new HashMap<>();
        result.put("sourceVideoList",resultSourceVideoList);
        return JsonTool.genJson(RetEnum.SUCCESS, result);
    }

    /**
     * 上传素材
     * @param params
     * @return
     */
    @Override
    @Transactional
    public String create(Map<String, String> params) {
        Integer userId = Integer.parseInt(params.get("userId"));
        String videoIds = ObjectTool.stringOrNull(params.get("video_ids"));
        if(StringUtils.isBlank(videoIds)){   // 请求参数错误
            return JsonTool.genJson(RetEnum.REQUEST_PARAM_ERROR);
        }
        List<String> videoIdList =  new ArrayList<>();
        try{
            videoIdList = Arrays.asList(videoIds.split(","));
        }catch (Exception e){
            _log.error(">>>>>>>>>>>>>>>>>>解析参数错误,请求参数:{}, 错误信息:{}",params.toString(),e);
        }
        if(videoIdList.size() < 1){         // 请求参数错误
            return JsonTool.genJson(RetEnum.REQUEST_PARAM_ERROR);
        }
        ArrayList<Map<String, Object>> resultSourceVideoList = new ArrayList<>();
        Date now = new Date();
        for(String videoId : videoIdList){
            if(StringUtils.isNotBlank(videoId)){
                Video video = new Video();
                video.setStatus(0);
                video.setVideoId(videoId);
                video.setMadeTime(now);
                video.setCreateTime(now);
                Video tempVideo = videoCacheDao.insertSelective(video);
                UserSourceVideo sourceVideo = new UserSourceVideo();
                sourceVideo.setUserId(userId);
                sourceVideo.setVideoId(tempVideo.getId());
                sourceVideo.setCreateTime(now);
                userSourceVideoDao.insertSelective(sourceVideo);
                Map<String, Object> resultSourceVideo = new HashMap<>();
                resultSourceVideo.put("id",sourceVideo.getId());
                resultSourceVideo.put("videoId",video.getId());
                // 单例结果
                Map<String, Object> singleResultVideo = new HashMap<>();
                singleResultVideo.put("sourceVideo", resultSourceVideo);
                resultSourceVideoList.add(singleResultVideo);
            }
        }
        _log.info(">>>>>>>>>>>>>素材库上传完成! success, 请求参数:{}",params.toString());
        Map<String, Object> result = new HashMap<>();
        result.put("sourceVideoList",resultSourceVideoList);
        return JsonTool.genJson(RetEnum.SUCCESS, result);
    }

    /**
     * 删除自己素材库的视频
     * 只删除source_video的记录,不删除video
     * @param params
     * @return
     */
    @Override
    @Transactional
    public String delete(Map<String, String> params) {
        Integer userId = Integer.parseInt(params.get("userId"));
        String sourceIds = ObjectTool.stringOrNull(params.get("sourceIds"));
        if(StringUtils.isBlank(sourceIds)){     // 请求参数错误
            return JsonTool.genJson(RetEnum.REQUEST_PARAM_ERROR);
        }
        List<String> sourceIdList =  new ArrayList<>();
        try{
            sourceIdList = Arrays.asList(sourceIds.split(","));
        }catch (Exception e){
            _log.error(">>>>>>>>>>>>>>>>>>解析参数错误,请求参数:{}, 错误信息:{}",params.toString(),e);
        }
        if(sourceIdList.size() < 1){         // 请求参数错误
            return JsonTool.genJson(RetEnum.REQUEST_PARAM_ERROR);
        }
        for(String sourceId : sourceIdList){
            if(StringUtils.isNotBlank(sourceId)){   // 删除
                userSourceVideoDao.deleteByPrimaryKey(Integer.parseInt(sourceId));
            }
        }
        return JsonTool.genJson(RetEnum.SUCCESS);
    }

    /**
     * 获取分享链接
     * @param params
     * @return
     */
    @Override
    public String sahreLink(Map<String, String> params) {
        Integer userId = Integer.parseInt(params.get("userId"));
        String videoIds = ObjectTool.stringOrNull(params.get("videoIds"));
        if(StringUtils.isBlank(videoIds)){   // 请求参数错误
            return JsonTool.genJson(RetEnum.REQUEST_PARAM_ERROR);
        }
        List<String> videoIdList =  new ArrayList<>();
        try{
            videoIdList = Arrays.asList(videoIds.split(","));
        }catch (Exception e){
            _log.error(">>>>>>>>>>>>>>>>>>解析参数错误,请求参数:{}, 错误信息:{}",params.toString(),e);
        }
        if(videoIdList.size() < 1){         // 请求参数错误
            return JsonTool.genJson(RetEnum.REQUEST_PARAM_ERROR);
        }
        for(String videoId : videoIdList){
            if(StringUtils.isNotBlank(videoId)){
                Video video = videoCacheDao.selectByPrimaryKey(Integer.parseInt(videoId));
                if(video == null || video.getStatus().intValue() != 1){     // 视频不存在或者不能播放
                    _log.info(">>>>>>>>>>>>>获取分享链接, 该视频无法播放, videoId:{}",videoId);
                    return JsonTool.genJson(RetEnum.VIDEO_COLLECTION_PART_NOT_PLAY);    // 存在无法播放的视频
                }
            }
        }

        // 存入分享记录
        ShareVideoLog log = new ShareVideoLog();
        log.setVideoIds(videoIds);
        log.setCreateTime(new Date());
        log.setUserId(userId);
        shareVideoLogDao.insertSelective(log);
        
        // 拼接分享链接
        Hashids hashids = new Hashids(ConfigConstant.HASH_IDS_SECRET_KEY, ConfigConstant.HASH_IDS_VALUE_LENGTH);
        String shareId = hashids.encode(log.getId());
        String wx_domain = configCacheDao.selectByCkey(ConfigConstant.WX_DOMAIN).getCvalue();
        String shareUrl = wx_domain+"/" + ConfigConstant.SHARE_MAPPING_PATH_VIDEO + "?shareId=" + shareId;
        Map<String, Object> result = new HashMap<>();
        result.put("shareUrl",shareUrl);
        return JsonTool.genJson(RetEnum.SUCCESS, result);
    }

    /**
     * 收藏素材视频
     * @param paramMap
     * @return
     */
    @Override
    public String collect(Map<String, String> paramMap) {
        String hashUserId = ObjectTool.stringOrNull(paramMap.get("userId"));
        String hashShareId = ObjectTool.stringOrNull(paramMap.get("shareId"));
        if(hashUserId == null || hashShareId == null){  // 请求参数错误
            return JsonTool.genJson(RetEnum.REQUEST_PARAM_ERROR);
        }
        Integer userId = -1;
        Integer shareId = -1;
        Hashids hashids = new Hashids(ConfigConstant.HASH_IDS_SECRET_KEY, ConfigConstant.HASH_IDS_VALUE_LENGTH);
        try{
            userId = Integer.parseInt(String.valueOf(hashids.decode(hashUserId)[0]));
            shareId = Integer.parseInt(String.valueOf(hashids.decode(hashShareId)[0]));
        }catch (Exception e){
            _log.error(">>>>>>>>>>>>>hashIds解密出错,请求参数:{},错误信息:{}",paramMap.toString(),e);
        }

        if(userId < 0 || shareId < 0){
            return JsonTool.genJson(RetEnum.REQUEST_PARAM_ERROR);
        }
        User user = userCacheDao.selectByPrimaryKey(userId);
        ShareVideoLog shareVideoLog = shareVideoLogDao.selectByPrimaryKey(shareId);
        if(user == null){
            return JsonTool.genJson(RetEnum.OAUTH_CHECK_INEXISTENCE);   // 用户不存在
        }
        if(shareVideoLog == null){
            return JsonTool.genJson(RetEnum.REQUEST_DATA_NOT_EXIST);    // 查找的数据不存在
        }

        String videoIds = shareVideoLog.getVideoIds();
        List<String> videoIdList =  new ArrayList<>();
        try{
            videoIdList = Arrays.asList(videoIds.split(","));
        }catch (Exception e){
            _log.error(">>>>>>>>>>>>>>>>>>解析参数错误,请求参数:{}, 错误信息:{}",videoIds,e);
        }
        for(String videoId : videoIdList){
            if(StringUtils.isNotBlank(videoId)){
                try{
                    Video video = videoCacheDao.selectByPrimaryKey(Integer.parseInt(videoId));
                    if(video != null && video.getStatus().intValue() > 0){
                        Map<String, Object> daoMap = new HashMap<>();
                        daoMap.put("userId",userId);
                        daoMap.put("videoId",videoId);
                        UserSourceVideo sourceVideo = userSourceVideoDao.selectByParams(daoMap);
                        if(sourceVideo == null){            // 新增
                            sourceVideo = new UserSourceVideo();
                            sourceVideo.setUserId(userId);
                            sourceVideo.setVideoId(video.getId());
                            sourceVideo.setCreateTime(new Date());
                            userSourceVideoDao.insertSelective(sourceVideo);
                        }else {                             // 修改时间
                            sourceVideo.setCreateTime(new Date());
                            userSourceVideoDao.updateByPrimaryKeySelective(sourceVideo);
                        }
                    }
                }catch (Exception e){
                    _log.error(">>>>>>>>>>>>收藏素材库发生错误,videoId:{}, 错误信息:{}",videoId,e);
                }
            }
        }
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> resultUser = new HashMap<>();
        resultUser.put("mobile",user.getMobile());
        result.put("user",resultUser);
        return JsonTool.genJson(RetEnum.SUCCESS,result);
    }

    /**
     * 获取分享的视频
     * @param paramMap
     * @return
     */
    @Override
    public String shareVideoList(Map<String, String> paramMap) {
        String hashShareId = ObjectTool.stringOrNull(paramMap.get("shareId"));
        Integer start = Integer.parseInt(paramMap.get("start"));
        Integer rows = Integer.parseInt(paramMap.get("rows"));
        Integer page = Integer.parseInt(paramMap.get("page"));
        if(hashShareId == null){
            return JsonTool.genJson(RetEnum.REQUEST_PARAM_ERROR);
        }

        Integer shareId = -1;
        Hashids hashids = new Hashids(ConfigConstant.HASH_IDS_SECRET_KEY, ConfigConstant.HASH_IDS_VALUE_LENGTH);
        try{
            shareId = Integer.parseInt(String.valueOf(hashids.decode(hashShareId)[0]));
        }catch (Exception e){
            _log.error(">>>>>>>>>>>>>hashIds解密出错,请求参数:{},错误信息:{}",paramMap.toString(),e);
        }
        if(shareId < 0){
            return JsonTool.genJson(RetEnum.REQUEST_PARAM_ERROR);
        }
        ShareVideoLog shareVideoLog = shareVideoLogDao.selectByPrimaryKey(shareId);
        if(shareVideoLog == null){
            return JsonTool.genJson(RetEnum.REQUEST_DATA_NOT_EXIST);    // 查找的数据不存在
        }
        String videoIds = shareVideoLog.getVideoIds();
        List<String> videoIdList =  new ArrayList<>();
        try{
            videoIdList = Arrays.asList(videoIds.split(","));
        }catch (Exception e){
            _log.error(">>>>>>>>>>>>>>>>>>解析参数错误,请求参数:{}, 错误信息:{}",videoIds,e);
        }

        // 获取视频信息
        List<Map<String,Object>> resultSourceVideoList = new ArrayList<>();
        int end = videoIdList.size();
        if(end - rows*page > 10){   // 分页
            end = rows*page;
        }
        for(int i = start ; i < end ; i++){      // video的主键key
            String videoId = videoIdList.get(i);
            Map<String, Object> resultVideo = new HashMap<>();

            String playUrl = "";
            String coverUrl = "";
            String duration = "";
            try{
                Video video = videoCacheDao.selectByPrimaryKey(Integer.parseInt(videoId));
                if(video != null && video.getStatus() > 0){ // 视频可以正常播放
                    VideoInfoBean videoInfoBean = JSON.parseObject(video.getVideoInfo(), VideoInfoBean.class);
                    playUrl = videoInfoBean.getPlayUrl();
                    coverUrl = videoInfoBean.getCoverUrl();
                    duration = videoInfoBean.getDuration();
                }
            }catch (Exception e){
                _log.error(">>>>>>>>>>>>收藏素材库发生错误,videoId:{}, 错误信息:{}",videoId,e);
            }
            resultVideo.put("id",videoId);
            resultVideo.put("playUrl",playUrl);
            resultVideo.put("coverUrl",coverUrl);
            resultVideo.put("duration",duration);

            Map<Object, Object> singleResultVideo = new HashMap<>();
            singleResultVideo.put("video",resultVideo);
            resultSourceVideoList.add(resultVideo);
        }

        // 获取用户信息
        String headPortraitUrl = "";
        String nickName = "";
        try{
            Integer userId = shareVideoLog.getUserId();
            User user = userCacheDao.selectByPrimaryKey(userId);
            nickName = user.getNickName();

            // 获取图片alitool
            String OSS_CDN = configCacheDao.selectByCkey(ConfigConstant.OSS_CDN).getCvalue();
            String ACCESS_ID = configCacheDao.selectByCkey(ConfigConstant.ACCESS_ID).getCvalue();
            String ACCESS_KEY = configCacheDao.selectByCkey(ConfigConstant.ACCESS_KEY).getCvalue();
            String BUCKET_ID = configCacheDao.selectByCkey(ConfigConstant.BUCKET_ID).getCvalue();
            // 查看图片用OSS_CDN
            AliTool aliTool = AliTool.getInstance(OSS_CDN, ACCESS_ID, ACCESS_KEY, BUCKET_ID);
            headPortraitUrl = aliTool.getAccessURL(user.getHeadPortraitId());
        }catch (Exception e){
            _log.error(">>>>>>>>>>>>>获取用户信息出错, userId:{}, 错误信息:{}", shareVideoLog.getUserId(), e);
        }

        // 用户信息
        Map<String, Object> resultUser = new HashMap<>();
        resultUser.put("headPortraitUrl", headPortraitUrl);
        resultUser.put("nickName", nickName);
        // 视频总数
        Map<String, Object> resultCount = new HashMap<>();
        resultCount.put("videoCount", videoIdList.size());

        Map<String, Object> result = new HashMap<>();
        result.put("count", resultCount);
        result.put("user", resultUser);
        result.put("sourceVideoList", resultSourceVideoList);
        return JsonTool.genJson(RetEnum.SUCCESS, result);
    }

    public static void main(String[] args) {
        Hashids hashids = new Hashids(ConfigConstant.HASH_IDS_SECRET_KEY, ConfigConstant.HASH_IDS_VALUE_LENGTH);

        String encode = hashids.encode(17);

        System.out.println(encode);

        long ss = hashids.decode("aO8Kz6X0Bb0YLgroWZ")[0];
        System.out.println(ss);
    }
}
